﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Reflection;

namespace SpeakerRecognition
{
    public partial class Form_Main : Form
    {
        // instance of the logic layer manager 
        private LogicLayerManager logicLayerManager;
        
        ToolTip labelsToolTip;

        private string pathToXml = "";
        
        private Color[] colorArray = { Color.Lime, Color.Magenta, Color.Crimson, Color.Cyan,Color.Orange ,Color.Yellow, Color.DarkGreen, Color.Coral, Color.DarkRed, Color.Gold, Color.Blue, Color.Fuchsia, Color.Green, Color.IndianRed, Color.Violet, Color.Turquoise, Color.SteelBlue, Color.Silver, Color.Salmon, Color.SandyBrown, Color.SeaGreen, Color.PapayaWhip, Color.Olive, Color.Orange, Color.Orchid, Color.MediumSpringGreen };
        
        private System.Media.SoundPlayer myPlayer;

        public Form_Main()
        {
            try
            {
                logicLayerManager = new LogicLayerManager();
                labelsToolTip = new ToolTip(new System.ComponentModel.Container());
                
                InitializeComponent();
                // get the project's current dir for input Wav files
                String projPath = getProjectDir();
                if (projPath != "")
                {
                    CNetHelpProvider.HelpNamespace = projPath + "CHM\\SpeakerRecognition.chm";
                    openFileDialog_XML.InitialDirectory = projPath + "Results\\";
                    saveFileDialog_Xml.InitialDirectory = projPath + "Results\\";
                    // check if the directory exists
                    string path = projPath + "Inputs\\";
                    openFileDialog_wavFiles.InitialDirectory = path;
                }
               // create a player to be used in the application
                myPlayer = new System.Media.SoundPlayer();
                openFileDialog_wavFiles.Title = "Select a Wave Sound File";
                zedGraphControl_Clustering.Enabled = false;
                initializeLogicLayerParameters();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Error in Form_Main! For more information: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        /// <summary>
        /// Get the main project path on local disk
        /// </summary>
        /// <returns></returns>
        private String getProjectDir()
        {
            // get the project's current dir for input Wav files
            String path = System.Environment.CurrentDirectory;
            if (path.IndexOf("SpeakerRecognition") != -1)
            {
                path = path.Substring(0, path.LastIndexOf("SpeakerRecognition"));
                path = path + "SpeakerRecognition\\";
                // check if the directory exists
                if (Directory.Exists(path))
                    return path;
            }
            return "";
        }

        /// <summary>
        /// 
        /// </summary>
        private void initializeLogicLayerParameters()
        {
            try
            {
                logicLayerManager.WindowType = comboBox_WindowType.Text;
                logicLayerManager.Alpha = (double)numericUpDown_Alpha.Value;
                logicLayerManager.WinSize = Int16.Parse((String)comboBox_windowSize.Text);
                String overlap = (String)comboBox_Overlap.Text;
                overlap = overlap.Substring(0, overlap.Length - 1);
                logicLayerManager.OverLap = logicLayerManager.WinSize * Int16.Parse(overlap) / 100;
                logicLayerManager.UsingHamming = checkBox_Windowing.Checked;
                logicLayerManager.UseStripSilence = checkBox_StripSilence.Checked;
                logicLayerManager.NumberOfClusters = (int)numericUpDown_numberOfClusters.Value;
                logicLayerManager.RealOnly = checkBox_FFT.Checked;
                logicLayerManager.UsingMelFilter = checkBox_StripSilence.Checked;
                logicLayerManager.PowMagnitude = checkBox_Log.Checked;
                logicLayerManager.UseFirstCoeffAC = checkBox_MFCC_AC.Checked;
                logicLayerManager.GetHighFreq = !checkBox_MFCC_Low.Checked;
                logicLayerManager.NumberOfMFCC = Int16.Parse((String)comboBox_numberOfMFCC.Text);
                String distance = (String)comboBox_Distance.Text;
                switch (distance)
                {
                    case "Manhattan":
                        logicLayerManager.DistanceType = DistanceMeasurement.ManhattanDistance;
                        break;
                    case "Euclidean":
                        logicLayerManager.DistanceType = DistanceMeasurement.EuclidianDistance;
                        break;
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Error in initializeLogicLayerParameters! For more information: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        /// <summary>
        /// 
        /// </summary>
        private void reflectLogicLayerParametersToGui()
        {
            try
            {
                comboBox_WindowType.Text = logicLayerManager.WindowType;
                numericUpDown_Alpha.Text =  "" + logicLayerManager.Alpha;
                comboBox_windowSize.Text = "" + logicLayerManager.WinSize;
                comboBox_Overlap.Text = "" + ((((double)logicLayerManager.OverLap / logicLayerManager.WinSize)) * 100) + "%";
                checkBox_Windowing.Checked = logicLayerManager.UsingHamming;
                checkBox_StripSilence.Checked = logicLayerManager.UseStripSilence ;
                numericUpDown_numberOfClusters.Value = logicLayerManager.NumberOfClusters;
                checkBox_FFT.Checked = logicLayerManager.RealOnly;
                checkBox_Log.Checked = logicLayerManager.PowMagnitude;
                checkBox_MFCC_AC.Checked = logicLayerManager.UseFirstCoeffAC;
                checkBox_MFCC_Low.Checked = !logicLayerManager.GetHighFreq;
                comboBox_numberOfMFCC.Text = "" + logicLayerManager.NumberOfMFCC;
                switch (logicLayerManager.DistanceType)
                {
                    case DistanceMeasurement.ManhattanDistance:
                        comboBox_Distance.Text = "Manhattan";
                        break;
                    case DistanceMeasurement.EuclidianDistance:
                        comboBox_Distance.Text = "Euclidean";
                        break;
                }
                listBox_wav_Files.Items.Clear();
                listBox_wav_Files.Items.AddRange(logicLayerManager.InputFilesNamesOnly);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Error in initializeLogicLayerParameters! For more information: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        /// <summary>
        /// In case the browse was clicked
        /// The open files dialog is filtered for Wav files only
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void browseFiles(object sender, EventArgs e)
        {
            try
            {
                openFileDialog_wavFiles.Filter = "Wav Files(*.wav)|*.wav";
                openFileDialog_wavFiles.ShowDialog(); 
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Error in browseFiles! For more information: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_remove_files_Click(object sender, EventArgs e)
        {
            try
            {
                int sizRem = listBox_wav_Files.SelectedIndices.Count;
                if (sizRem == logicLayerManager.InputFilesNamesOnly.Length)
                {
                    button_remove_files.Enabled = false;
                }
                else
                {
                    button_remove_files.Enabled = true;
                }

                string[] tempNames = new string[logicLayerManager.InputFilesNamesOnly.Length - sizRem];
                string[] tempInp = new string[logicLayerManager.InputFilesNamesOnly.Length - sizRem];
                // check which files need to be copied
                for (int j = 0,i = 0; i < logicLayerManager.InputFilesNamesOnly.Length; i++)
                {
                    if (!listBox_wav_Files.SelectedItems.Contains(logicLayerManager.InputFilesNamesOnly[i]))
                    {
                        tempNames[j] = logicLayerManager.InputFilesNamesOnly[i];
                        tempInp[j++] = logicLayerManager.InputFiles[i];
                    }
                    
                }
                // remove all files from list 
                while (listBox_wav_Files.SelectedIndices.Count > 0)
                {
                    listBox_wav_Files.Items.RemoveAt(listBox_wav_Files.SelectedIndices[0]);
                }
                // update arrays
                logicLayerManager.InputFiles = tempInp;
                logicLayerManager.InputFilesNamesOnly = tempNames;

            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Error in remove files! For more information: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void addFilesToList(object sender, CancelEventArgs e)
        {
            try
            {
                // clear file names from list if the browse files was selected again
                listBox_wav_Files.Items.Clear();
                //logicLayerManager = new LogicLayerManager();      // No need to create new logic layer manager
                //initializeLogicLayerParameters();
                String[] nameOnly = new String[openFileDialog_wavFiles.FileNames.Length];

                // add new files to list with index number
                for (int i = 0; i < openFileDialog_wavFiles.FileNames.Length; i++)
                {
                    String filename = openFileDialog_wavFiles.FileNames[i];
                    filename = filename.Substring(filename.LastIndexOf('\\') + 1);
                    nameOnly[i] = filename;
                    listBox_wav_Files.Items.Add(filename);
                }
                // add file names to logic layer to save data
                logicLayerManager.InputFiles = openFileDialog_wavFiles.FileNames;
                logicLayerManager.InputFilesNamesOnly = nameOnly;
                button_remove_files.Enabled = true;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Error in addFilesToList! For more information: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void comboBox_windowSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            String winSize = (String)comboBox_windowSize.SelectedItem;
            logicLayerManager.WinSize = Int16.Parse(winSize);
            String overlap = (String)comboBox_Overlap.SelectedItem;
            overlap = overlap.Substring(0, overlap.Length - 1);
            logicLayerManager.OverLap = logicLayerManager.WinSize * Int16.Parse(overlap) / 100;
        }

        private void comboBox_Overlap_SelectedIndexChanged(object sender, EventArgs e)
        {
            String overlap = (String)comboBox_Overlap.SelectedItem;
            overlap = overlap.Substring(0, overlap.Length - 1);
            logicLayerManager.OverLap = logicLayerManager.WinSize * Int16.Parse(overlap) / 100;
        }

        private void checkBox_Hamming_CheckedChanged(object sender, EventArgs e)
        {
            logicLayerManager.UsingHamming = checkBox_Windowing.Checked;
        }

        private void checkBox_StripSilence_CheckedChanged(object sender, EventArgs e)
        {
            logicLayerManager.UseStripSilence = checkBox_StripSilence.Checked;
        }

        private void checkBox_FFT_CheckedChanged(object sender, EventArgs e)
        {
            logicLayerManager.RealOnly = checkBox_FFT.Checked;
        }

        private void checkBox_Log_CheckedChanged(object sender, EventArgs e)
        {
            logicLayerManager.PowMagnitude = checkBox_Log.Checked;
        }

        private void comboBox_numberOfMFCC_SelectedIndexChanged(object sender, EventArgs e)
        {
            String mfccNum = (String)comboBox_numberOfMFCC.SelectedItem;
            logicLayerManager.NumberOfMFCC = Int16.Parse(mfccNum);
        }

        private void checkBox_MFCC_AC_CheckedChanged(object sender, EventArgs e)
        {
            logicLayerManager.UseFirstCoeffAC = checkBox_MFCC_AC.Checked;
        }

        private void checkBox_MFCC_Low_CheckedChanged(object sender, EventArgs e)
        {
            logicLayerManager.GetHighFreq = !checkBox_MFCC_Low.Checked;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox_Distance_SelectedIndexChanged(object sender, EventArgs e)
        {
            String distance = (String)comboBox_Distance.SelectedItem;
            switch (distance)
            {
            case "Manhattan":
                    logicLayerManager.DistanceType = DistanceMeasurement.ManhattanDistance;
            	break;

            case "Euclidean":
                logicLayerManager.DistanceType = DistanceMeasurement.EuclidianDistance;
            	break;
            }
        }

        private void button_Execute_Click(object sender, EventArgs e)
        {
            try
            {
                // check if no files in the list
                if (listBox_wav_Files.Items.Count == 0)
                {
                    MessageBox.Show("Please select input WAV files !", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // check if number of MFCC is less then winsize
                if (logicLayerManager.WinSize <= logicLayerManager.NumberOfMFCC)
                {
                    MessageBox.Show("Number of MFCC should be lower then window size !", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                // check all files in list are valid
                for (int i = 0; i < logicLayerManager.InputFilesNamesOnly.Length; i++)
                {
                    if (!File.Exists(logicLayerManager.InputFiles[i]))
                    {
                        MessageBox.Show("Error while trying to run process! File name does not exist: " + logicLayerManager.InputFiles[i], "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

                logicLayerManager.clearLogicManagerResults();
                progressBar_Main.Value = 0;
                    // set all controls to be locked
                updateEnableStatus(false);
                label_Progress_File.Text = "Processing...";
                label_Progress_File.Update();
                comboBox_Result_ClusterNumber.Items.Clear();
                for (int i = 0; i < logicLayerManager.NumberOfClusters; i++)
                {
                    comboBox_Result_ClusterNumber.Items.Add(i + 1);
                }
                //comboBox_Result_ClusterNumber.Items.Add("centers");
                logicLayerManager.runCompleteProcess(progressBar_Main, label_Progress_File);
                updateEnableStatus(true);
                saveToolStripMenuItem1.Enabled = true;
                saveAsToolStripMenuItem1.Enabled = true;
                updateResultsDataGrid();
                label_Progress_File.Text = "Process completed...";
                updateDistanceDataGrid();
                zedGraphControl_Clustering.Visible = true;
                //select the first cluster to show result
                comboBox_Result_ClusterNumber.SelectedIndex = 0;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Error in main program! For more information: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="b"></param>
        private void updateEnableStatus(bool b) 
        {
            menuStrip_Main.Enabled = b;
            comboBox_Result_ClusterNumber.Enabled = b;
            groupBox_Settings.Enabled = b;
           // listBox_wav_Files.Enabled = b;
            button_Wav_File_Browser.Enabled = b;
            button_Execute.Enabled = b;
            groupBox_Windowing.Enabled = b;
            comboBox_Result_ClusterNumber.Enabled = b;
            zedGraphControl_Clustering.Enabled = b;
            button_remove_files.Enabled = b;
        }
        /// <summary>
        /// 
        /// </summary>
        private void updateResultsDataGrid()
        {
            if (dataGridView_results != null)
            {
                DataTable inventory = logicLayerManager.createResultsDataTable();
                // Now bind this data table to the grid.
                dataGridView_results.DataSource = inventory;
                dataGridView_results.AutoResizeColumns();
            }
            logicLayerManager.CreateGraph(zedGraphControl_Clustering);
        }
        /// <summary>
        /// 
        /// </summary>
        private void updateDistanceDataGrid()
        {
            if (dataGridView_Distance != null)
            {
                DataTable inventory = logicLayerManager.createDistanceDataTable();
                // Now bind this data table to the grid.
                dataGridView_Distance.DataSource = inventory;         
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void numericUpDown_Alpha_ValueChanged(object sender, EventArgs e)
        {
            logicLayerManager.Alpha = (double)numericUpDown_Alpha.Value;
        }

        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            logicLayerManager.NumberOfClusters = (int)numericUpDown_numberOfClusters.Value;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_Play_Click(object sender, EventArgs e)
        {
            if (listBox_wav_Files.Items.Count != 0)
                if (listBox_wav_Files.SelectedItem != null)
                {
                    button_Play.Enabled = false;
                    String fileName = logicLayerManager.InputFiles[listBox_wav_Files.SelectedIndex];
                    myPlayer.SoundLocation = @fileName;
                    myPlayer.Play();
                }
            button_Play.Enabled = true;
            myPlayer.Dispose();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_Stop_Click(object sender, EventArgs e)
        {
            if (listBox_wav_Files.Items.Count != 0)
                if (listBox_wav_Files.SelectedItem != null)
                {
                    myPlayer.Stop();
                }
            button_Play.Enabled = true;
            myPlayer.Dispose();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_displaySound_Click(object sender, EventArgs e)
        {
            if (listBox_wav_Files.Items.Count == 0)
                return;
            if (listBox_wav_Files.SelectedItem == null)
                return;
            String fileName = logicLayerManager.InputFiles[listBox_wav_Files.SelectedIndex];
            double[] wave = logicLayerManager.getWavData(fileName);
 
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="wave"></param>
        /// <param name="col"></param>
        /// <param name="pictureBox"></param>
        /// <param name="canvasTimeDomain"></param>
        /// <param name="type"></param>
        private void drawTimeDomainOutputData(double[] wave, Color col, PictureBox pictureBox, Bitmap canvasTimeDomain, int type, double maxYval)
        {
            Graphics offScreenDC = Graphics.FromImage(canvasTimeDomain);
            SolidBrush brush = new System.Drawing.SolidBrush
                        (Color.FromArgb(0, 0, 0));
            Pen pen = new System.Drawing.Pen(col);

            // Determine channel boundaries
            long width = canvasTimeDomain.Width;
            long center = canvasTimeDomain.Height / 2;
            long height = canvasTimeDomain.Height;
            //offScreenDC.DrawLine(pen, 0, center, width, center);
            long left = 0;
            long top = 0;
            long right = width;
            long bottom = height;
            // Draw channel
            double yCenter = (bottom - top) / 2;
            double yScale = 0.5 * (bottom - top) / maxYval;
            //  for FFT 
            if (type == 1)
            {
                yScale = (-1) * (bottom - top) / maxYval;
                yCenter = bottom - 4;
            }
                // for MFFC display graph
            if (type == 2)
            {
                yScale = (-1) * (bottom - top)/ maxYval;
                yCenter = bottom - 4;
            }
            // a 16 bit sample has values from -32768 to 32767
            long xPrev = 0, yPrev = 0;
            for (long xAxis = left; (xAxis < right) && (xAxis < wave.Length); xAxis++)
            {
                long xStep = wave.Length / (right - left) * xAxis;
                if (wave.Length < width)
                    xStep = xAxis;
                long yAxis = (long)(yCenter + (wave[xStep] * yScale));
                if (xAxis == 0)
                {
                    xPrev = 0;
                    yPrev = yAxis;
                }
                else
                {
                    offScreenDC.DrawLine(pen, xPrev, yPrev, xAxis, yAxis);
                    xPrev = xAxis;
                    yPrev = yAxis;
                }
            }

            // Clean up
            pictureBox.Image = canvasTimeDomain;
            offScreenDC.Dispose();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox_Result_ClusterNumber_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox_Result_ClusterNumber.Items.Count == 0)
                return;
            // Set up for drawing in the Wav Data Picture Box
            Bitmap canvasWav = new Bitmap(pictureBox_Wav_data.Width, pictureBox_Wav_data.Height);

            // Set up for drawing in the FFT Data Picture Box
            Bitmap canvasFFT = new Bitmap(pictureBox_FFT_Data.Width, pictureBox_FFT_Data.Height);

            // Set up for drawing in the MFCC Data Picture Box
            Bitmap canvasMFCC = new Bitmap(pictureBox_MFCC_Data.Width, pictureBox_MFCC_Data.Height);

            int selectedCluster = comboBox_Result_ClusterNumber.SelectedIndex;
            int[] filesInCluster = (int[])logicLayerManager.Results[selectedCluster];

            double maxWav = -1, maxFFT = -1, maxMFCC = -1,tempMax;

            for (int i = 0; i < filesInCluster.Length; i++)
            {
                tempMax  = logicLayerManager.findMaxValueInArray(logicLayerManager.SaveData[filesInCluster[i]].WavData);
                if (tempMax > maxWav)
                    maxWav = tempMax;

                tempMax  = logicLayerManager.findMaxValueInArray(logicLayerManager.SaveData[filesInCluster[i]].FftDataOneDim);
                if (tempMax > maxFFT)
                    maxFFT = tempMax;
                
                tempMax  = logicLayerManager.findMaxValueInArray((double[])logicLayerManager.InputMFCCDataToPAM[filesInCluster[i]]);
                if (tempMax > maxMFCC)
                    maxMFCC = tempMax;
            }

            for (int i = 0; i < filesInCluster.Length; i++ )
            {
                drawTimeDomainOutputData(logicLayerManager.SaveData[filesInCluster[i]].WavData, colorArray[i], pictureBox_Wav_data, canvasWav,0,maxWav);
                drawTimeDomainOutputData(logicLayerManager.SaveData[filesInCluster[i]].FftDataOneDim, colorArray[i], pictureBox_FFT_Data, canvasFFT,1,maxFFT);
                drawTimeDomainOutputData((double[])logicLayerManager.InputMFCCDataToPAM[filesInCluster[i]], colorArray[i], pictureBox_MFCC_Data, canvasMFCC,2,maxMFCC);
            }
            updateColorsInRichTextBox(selectedCluster, filesInCluster);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="selectedCluster"></param>
        /// <param name="filesInCluster"></param>
        private void updateColorsInRichTextBox(int selectedCluster, int[] filesInCluster)
        {
            richTextBox_cluster_colors.Clear();
            for (int i = 0; i < filesInCluster.Length; i++)
            {
                richTextBox_cluster_colors.SelectionBackColor = colorArray[i];
                //richTextBox_cluster_colors.SelectionColor = colorArray[i];
                String temp = (i + 1) +". "+ logicLayerManager.InputFilesNamesOnly[filesInCluster[i]] + "\n";
                richTextBox_cluster_colors.AppendText(temp);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox_WindowType_SelectedIndexChanged(object sender, EventArgs e)
        {
            logicLayerManager.WindowType = comboBox_WindowType.Text;
            Bitmap ImageImp = null,Image = null;
            String winType = (String)comboBox_WindowType.Text;
            switch (winType)
            {
                case "Hamming":
                    Image = Properties.Resources.Hamming;
                    ImageImp = Properties.Resources.HammingImpulse;
                    break;
                case "Rectangular":
                    Image = Properties.Resources.Rectangular;
                    ImageImp = Properties.Resources.RectangularImpulse;
                    break;
                case "Hanning":
                    Image = Properties.Resources.Hanning;
                    ImageImp = Properties.Resources.HanningImpulse;
                    break;
                case "Cosine":
                    Image = Properties.Resources.Sine;
                    ImageImp = Properties.Resources.SineImpulse;
                    break;
                case "Gauss":
                    Image = Properties.Resources.Gauss;
                    ImageImp = Properties.Resources.GaussImpulse;
                    break;
                case "Nuttall":
                    Image = Properties.Resources.Nnuttall;
                    ImageImp = Properties.Resources.NnuttallImpulse;
                    break;
            }
            pictureBox_Window.Image = Image;
            pictureBox_WindowImpulse.Image = ImageImp;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveToolStripMenuItem1_DropDownItemClicked(object sender, EventArgs e)
        {
            try
            {
                if (pathToXml == "")
                {
                    String path = getProjectDir() + "Results\\Untitled.xml";
                    xmlHandler.saveFile(logicLayerManager, path);
                    this.Text = "Speaker Recognition System  -   Untitled.xml";
                }
                else
                    xmlHandler.saveFile(logicLayerManager, pathToXml);
            }
            catch (System.Exception ex)
            {

                MessageBox.Show("Error in save file! For more information: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("Do you want to close the application", "Close",
            MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
            if (dr == DialogResult.OK )
                Form_Main.ActiveForm.Close();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox aboutbox = new AboutBox();
            aboutbox.ShowDialog();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void contentsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(getProjectDir() + "CHM\\main.htm");
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openFileXML(object sender, CancelEventArgs e)
        {
            try
            {
                xmlHandler.loadFile(openFileDialog_XML.FileName, logicLayerManager);
                string fileName = openFileDialog_XML.FileName;
                pathToXml = fileName;
                fileName = fileName.Substring(fileName.LastIndexOf('\\') + 1, fileName.Length - fileName.LastIndexOf('\\') - 1);
                this.Text = "Speaker Recognition System  -   " + fileName;
                reflectLogicLayerParametersToGui();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Error in open file! For more information: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            openFileDialog_XML.Filter = "XML Files(*.xml)|*.xml";
            openFileDialog_XML.ShowDialog(); 
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveAsToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            saveFileDialog_Xml.Filter = "XML Files(*.xml)|*.xml";
            saveFileDialog_Xml.ShowDialog();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveXMLFile(object sender, CancelEventArgs e)
        {
            try
            {
                string fileName = saveFileDialog_Xml.FileName;
                String nameOnly = fileName.Substring(fileName.LastIndexOf('\\') + 1, fileName.Length - fileName.LastIndexOf('\\') - 1);
                xmlHandler.saveFile(logicLayerManager, fileName);
                this.Text = "Speaker Recognition System  -   " + nameOnly;

            }
            catch (System.Exception ex)
            {
               
                MessageBox.Show("Error in save file! For more information: " + ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
   
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dr = MessageBox.Show("This action will reset the application.\nDo you want to continue with the operation ?", "Warning", MessageBoxButtons.OKCancel , MessageBoxIcon.Warning);
                if (dr == DialogResult.OK)
                    Application.Restart();
                //comboBox_WindowType.Text = "Hamming";
                //numericUpDown_Alpha.Text = "0.95";
                //comboBox_windowSize.Text = "1024";
                //comboBox_Overlap.Text = "50%";
                //checkBox_Windowing.Checked = true;
                //checkBox_StripSilence.Checked = false;
                //numericUpDown_numberOfClusters.Value = 3;
                //checkBox_FFT.Checked = true;
                //checkBox_Log.Checked = false;
                //checkBox_MFCC_AC.Checked = false;
                //checkBox_MFCC_Low.Checked = true;
                //comboBox_numberOfMFCC.Text = "16";
                //comboBox_Distance.Text = "Manhattan";
                //listBox_wav_Files.Items.Clear();
                //logicLayerManager = new LogicLayerManager();
                //initializeLogicLayerParameters();
                //this.Text = "Speaker Recognition System";
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("Error in creating new configuration! For more information: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void label_StripSilence_MouseHover(object sender, EventArgs e)
        {
            labelsToolTip.SetToolTip(label_StripSilence, "This filter is separating  between \n Silence and voice");

        }

        private void label_Alpha_MouseHover(object sender, EventArgs e)
        {
            labelsToolTip.SetToolTip(label_Alpha, "Select alpha from list to Pre-Emphasis process ");
        }

        private void label_Real_only_MouseHover(object sender, EventArgs e)
        {
            labelsToolTip.SetToolTip(label_Real_only, "When this flag is selected \n  only the real part of the FFT process is taken");
        }


        private void label_MFCC_AC_MouseHover(object sender, EventArgs e)
        {
            labelsToolTip.SetToolTip(label_MFCC_AC, "When this flag is selected \n  the first coefficient  of the  FFT is taken ");

        }

        private void label_power_mag_MouseHover(object sender, EventArgs e)
        {
            labelsToolTip.SetToolTip(label_power_mag, "When this flag is selected \n  the coefficients squared  \n and before the log operation  is done ");
        }

        private void label_frequency_MouseHover(object sender, EventArgs e)
        {
            labelsToolTip.SetToolTip(label_frequency, "Take the low or the high  frequencies");
        }

        private void label_MFCC_number_MouseHover(object sender, EventArgs e)
        {
            labelsToolTip.SetToolTip(label_MFCC_number, "Select number of MFCC");
        }

        private void label_num_of_clusters_MouseHover(object sender, EventArgs e)
        {
            labelsToolTip.SetToolTip(label_num_of_clusters, "Select number of clusters");
        }

        private void label_Distance_MouseHover(object sender, EventArgs e)
        {
            labelsToolTip.SetToolTip(label_Distance, "Select distance type for PAM");
        }

        private void label_WindowType_MouseHover(object sender, EventArgs e)
        {
            labelsToolTip.SetToolTip(label_WindowType, "Select window type for windowing ");
        }

        private void label_windowSize_MouseHover(object sender, EventArgs e)
        {
            labelsToolTip.SetToolTip(label_windowSize, "Select window size ");
        }

        private void label_Overlap_MouseHover(object sender, EventArgs e)
        {
            labelsToolTip.SetToolTip(label_Overlap, "Select overlap between windows");
        }

        private void label_hamming_MouseHover(object sender, EventArgs e)
        {
            labelsToolTip.SetToolTip(label_hamming, "show window types");
        }

    }
}
